package com.springmybatis;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author shenguangyang
 */
public class MyFactoryBean implements FactoryBean<Object> {
    private SqlSession sqlSession;
    private final Class<?> mapper;

    public MyFactoryBean(Class<?> mapper) {
        this.mapper = mapper;
    }

    @Autowired
    public void setFactoryBean(SqlSessionFactory sqlSessionFactory) {
        sqlSessionFactory.getConfiguration().addMapper(mapper);
        this.sqlSession = sqlSessionFactory.openSession();
    }

    @Override
    public Object getObject() throws Exception {
        return sqlSession.getMapper(mapper);
    }

    @Override
    public Class<?> getObjectType() {
        return mapper;
    }
}
